<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\Api;
use app\common\model\Customer;
use app\common\model\Order;
use app\common\model\PublicStatus;
use app\common\model\Recharge;
use app\common\model\RechargeCoin;
use app\common\model\User;
use app\common\model\UserMoneyLog;
use app\common\model\VipPrice;
use general\AesUtil as GeneralAesUtil;
use Yansongda\Pay\Pay;
use general\Random;
use think\Exception;
use think\facade\Config;
use think\facade\Log;
use think\Request;

class PayCon extends Api
{
    //微信支付通知
    public function wxPayNoticeUrl()
    {
        try {
            Pay::config(Config::get("pay"));
            $data = Pay::wechat()->callback()->toArray();
            if ($data['event_type'] == 'TRANSACTION.SUCCESS') { //交易成功
                $resourceArr = $data['resource']['ciphertext'];
                if ($resourceArr['trade_state'] == 'SUCCESS') { //支付成功
                    $out_trade_no = $resourceArr['out_trade_no']; //订单号
                    //以下根据自己业务进行支付校验
                    $isflag = $this->payNoticeOrder($out_trade_no,'wxPay');
                    if (intval($isflag) == PublicStatus::PUBLIC_STATUS_ONE) {
                        return Pay::wechat()->success();
                    }
                }
                Log::write("微信支付-支付成功-回调数据: " . json_encode($data, JSON_UNESCAPED_UNICODE), 'wx_pay');
                return Pay::wechat()->success();
            }
            return Pay::wechat()->success();
        } catch (\Exception $e) {
            Log::write("异步回调发生错误: " . $e->getMessage(), 'wx_pay_error');
            return Pay::wechat()->success();
        }
    }


    public function payNoticeOrder($order_id,$type)
    {
        $order = Order::where('order_no', $order_id)->find();
        $pay_time = time();
        if (
            !$order || intval($order->status) !== 0
        ) {
            //如果订单状态异常直接退出
            Log::write("订单状态异常 ", 'pay_error');
            return Pay::wechat()->success();
        }
        //进行订单状态变更等支付成功操作
        $order->status = PublicStatus::PUBLIC_STATUS_ONE;
        $order->pay_time = $pay_time;
        $order->save();
        if (intval($order->recharge_type) !== PublicStatus::RECHARGE_TYPE_THREE) {
            $user = User::find($order->user_id);
            if (!$user) {
                //如果订单状态异常直接退出
                Log::write("未找到用户 ", 'pay_error');
                return Pay::wechat()->success();
            }
        }
        if (intval($order->recharge_type) == PublicStatus::RECHARGE_TYPE_ONE) { //vip充值
            //开通vip操作
            $user_type = $order->vip_type;
            $recharge_time = date('Y-m-d', $pay_time);
            if (!empty($user->expiration_time)) {
                $syday = day_remaining_fun($user->expiration_time); //获取剩余天数
            } else {
                $syday = 0;
            }
            //获取开通的vip天数
            $vip_day = VipPrice::with(['day'])->find($order->vip_price_id);
            if (!$vip_day) {
                //如果订单状态异常直接退出
                $this->error("错误");
                return Pay::wechat()->success();
            }
            $str = $type.'vip充值';
            $count_day = $syday + intval(($vip_day['day']['day'])); //计算剩余天数 +累加
            $expiration_time = expiration_time_fun($pay_time, $count_day);
            UserMoneyLog::vipayAfter($order->user_id, $order->pay_price, $recharge_time, $expiration_time, $user_type, $str, $order_id);
        } else if(intval($order->recharge_type) == PublicStatus::RECHARGE_TYPE_TWO) { //金币充值
            $recharge_coin_id = $order->recharge_coin_id;
            $recharge = RechargeCoin::find($recharge_coin_id);
            if (!$recharge) {
                Log::write("未找到金币数据 ", 'pay_error');
                return Pay::wechat()->success();
            }
            UserMoneyLog::payAfter($order->user_id, $recharge['coin'], $type.'金币充值', PublicStatus::USER_MONEY_STATUS_TAKEIN, $order_id);
        }else{
            //订阅
            $customer = Customer::where(['order_sn'=>$order_id,'subscribe_id'=>$order->subscribe_id])->find();
            if (!$customer) {
                Log::write("未找到客户信息 ", 'pay_error');
                return Pay::wechat()->success();
            }
            $customer->is_pay = PublicStatus::PUBLIC_STATUS_ONE;
            $customer->save();
            return Pay::wechat()->success();
        }
        return 1;
    }

    //支付宝回调
    public function aliNoticeUrl()
    {
        $data = $this->request->param();
        $str = json_encode($data);
        $arr = json_decode($str, true);

        //以下根据自己业务进行支付校验
        $order = Order::where('order_no', $arr['out_trade_no'])->find();
        $pay_time = time();
        if (!$order || intval($order->status) !== 0) {
            //如果订单状态异常直接退出
            Log::write("订单状态异常 ", 'ali_error');
            return "success";
        }
        // if (($order->pay_price) != $arr['buyer_pay_amount']) {
        //     //如果金额不匹配直接退出
        //     $this->error("错误");
        // }
        //进行订单状态变更等支付成功操作
        $order->status = PublicStatus::PUBLIC_STATUS_ONE;
        $order->pay_time = $pay_time;
        $order->save();
        //用户开通会员操作
        //1.获取用户信息
        if (intval($order->recharge_type) !== PublicStatus::RECHARGE_TYPE_THREE) {
            $user = User::find($order->user_id);
            if (!$user) {
                //如果订单状态异常直接退出
                Log::write("未找到用户 ", 'pay_error');
                return Pay::wechat()->success();
            }
        }
        if (intval($order->recharge_type) == PublicStatus::RECHARGE_TYPE_ONE) { //vip充值
            //开通vip操作
            $user_type = $order->vip_type;
            $recharge_time = date('Y-m-d', $pay_time);
            if (!empty($user->expiration_time)) {
                $syday = day_remaining_fun($user->expiration_time); //获取剩余天数
            } else {
                $syday = 0;
            }
            //获取开通的vip天数
            $vip_day = VipPrice::with(['day'])->find($order->vip_price_id);
            if (!$vip_day) {
                Log::write("vip天数错误 ", 'ali_error');
                return "success";
            }
            $count_day = $syday + intval(($vip_day['day']['day'])); //计算剩余天数 +累加
            $expiration_time = expiration_time_fun($pay_time, $count_day);
            UserMoneyLog::aliVipayAfter($order->user_id, $order->pay_price, $recharge_time, $expiration_time, $user_type, $str, $arr['out_trade_no']);
        } else if(intval($order->recharge_type) == PublicStatus::RECHARGE_TYPE_TWO){ //金币充值
            $recharge_coin_id = $order->recharge_coin_id;
            $recharge = RechargeCoin::find($recharge_coin_id);
            if (!$recharge) {
                Log::write("未找到金币数据 ", 'ali_error');
                return "success";
            }
            UserMoneyLog::aliPayAfter($order->user_id, $recharge['coin'], 'alipay金币充值', PublicStatus::USER_MONEY_STATUS_TAKEIN, $arr['out_trade_no']);
        }else{ //订阅
            //订阅
            $customer = Customer::where(['order_sn'=> $arr['out_trade_no'],'subscribe_id'=>$order->subscribe_id])->find();
            if (!$customer) {
                Log::write("未找到客户信息 ", 'ali_error');
                return "success";
            }
            $customer->is_pay = PublicStatus::PUBLIC_STATUS_ONE;
            $customer->save();
            return "success";
        }
        return "success";
    }
}
